package com.rerun.common.aspect;

import com.rerun.common.bean.Rest;
import com.rerun.entity.BugCollection;
import com.rerun.service.IBugCollectionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 处理异常返回.
 *
 * @author dax.
 * @version v1.0
 * @since 2017 /11/8 11:39
 */
@Aspect
@Component
public class ResponseExceptionAdvice {
    private static final Logger LOG = LoggerFactory.getLogger("AppException");
    @Resource
    private IBugCollectionService iBugCollectionService;

    /**
     * 环绕切入点.
     */
    @Pointcut("@annotation(com.rerun.common.anno.ResponseExceptionReturn)")
    public void exceptionAdvice() {
    }

    /**
     * Exception advise object.
     *
     * @param proceedingJoinPoint the proceeding join point
     * @return the object
     */
    @Around("exceptionAdvice()")
    public Object exceptionAdvise(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();

        Class returnType = method.getReturnType();

        try {
            return proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            String methodName = method.getName();
            String className = method.getDeclaringClass().toString();
            LOG.error(" 执行错误 method :" + methodName, throwable);
            BugCollection bugCollection = new BugCollection();
            String message = throwable.getMessage();
            bugCollection.setMessage(message);
            bugCollection.setMethod(methodName);
            bugCollection.setClassName(className);
            bugCollection.setCreateTime(new Date());
            try {
                iBugCollectionService.insert(bugCollection);

            } catch (Exception e) {
                LOG.debug(e.getMessage());
            }

            if (returnType == Rest.class) {
                return Rest.ServerError(message);
            }
        }
        return null;
    }
}
